<?php
/**
 * Created by PhpStorm.
 * User: lengbin
 * Date: 2019-01-14
 * Time: 10:35
 */

namespace common\helpers;

use lengbin\helper\excel\BaseImport;
use server\school\dao\Classroom;
use server\school\dao\School;
use server\user\dao\User;
use server\user\dao\UserTeacher;
use server\user\dao\UserTeacherClassroom;

class TeacherImport extends BaseImport
{

    private $_data = [];
    private $_limitUser = 900;

    public function __construct($file, $config)
    {
        parent::__construct($file, $config);
    }

    protected $school = [];
    protected $classroom = [];
    protected $user = [];
    protected $userTeacher = [];
    protected $userTeacherClassroom = [];
    protected $username = [];

    protected function import($rowData, $num)
    {
        $schoolId = $rowData['学校ID'];
        if (empty($this->school[$schoolId])) {
            $this->school[$schoolId] = (new School())->findOne($schoolId);
        }
        if (empty($this->school[$schoolId])) {
            var_export($schoolId);
            die;
        }
        $scope = $this->school[$schoolId]['type'];
        $classroomKey = $schoolId . $scope . (int)$rowData['入学年'] . '-' . $rowData['班级'];
        if (empty($this->classroom[$classroomKey])) {
            $this->classroom[$classroomKey] = (new Classroom())->find()->where([
                'school_id' => $schoolId,
                'name'      => $rowData['班级'],
                'year'      => $rowData['入学年'],
                'scope'     => $scope,
            ])->one();
        }
        if (empty($this->classroom[$classroomKey])) {
            var_export([
                'school_id' => $schoolId,
                'name'      => $rowData['班级'],
                'year'      => $rowData['入学年'],
                'scope'     => $scope,
            ]);
            die;
        }
        $user = new User();
        /**
         * user
         * user_teacher
         * classroom
         * user_teacher_classroom
         */
        $uid = $user->nextId();
        $time = time();
        $card = $rowData['身份证号'];
        $this->username[] = $card;
        $this->user[] = [
            $uid,
            $this->school[$schoolId]->id,
            $this->school[$schoolId]->name,
            $card,
            '$2y$13$GUyL/68yOC9756sW9v56F.ii7kKXA2AdtWpnP9pUpyc/U0UYy7Duy',
            'teacher',
            0,
            0,
            1,
            $time,
            $time,
        ];
        $sexint = (int) substr($card, 16, 1);
        $sex = $sexint % 2 === 0 ? 2 : 1;
        $this->userTeacher[] = [
            $uid,
            $sex,
            $rowData['姓名'],
            $scope,
            $time,
            $time,
        ];
        $this->userTeacherClassroom[] = [
            $uid,
            $this->classroom[$classroomKey]->id
        ];
        $this->classroom[$classroomKey]->user_id = $uid;
        $this->classroom[$classroomKey]->username = $card;

        // 已有数据 是否重复
//        if (in_array($rowData['mobile'], $this->_mobiles) || in_array($rowData['number'], $this->_numbers)) {
//            $this->csv[] = $num . ', 手机/编号(' . $rowData['mobile'] . '/ ' . $rowData['number'] . ')在导入列表中已重复';
//            return;
//        }
        $this->_data[] = $rowData;
    }

    protected function batchInsertUser($params)
    {
        return \Yii::$app->db->createCommand()->batchInsert(User::tableName(), [
            'id',
            'school_id',
            'school_name',
            'username',
            'password',
            'role',
            'is_stop',
            'is_delete',
            'is_active',
            'created_at',
            'updated_at',
        ], $params)->execute();
    }

    protected function batchInsertUserTeacher($params)
    {
        return \Yii::$app->db->createCommand()->batchInsert(UserTeacher::tableName(), [
            'id',
            'gender',
            'name',
            'scope',
            'created_at',
            'updated_at',
        ], $params)->execute();
    }

    protected function batchInsertUserTeacherClassroom($params)
    {
        return \Yii::$app->db->createCommand()->batchInsert(UserTeacherClassroom::tableName(), [
            'user_id',
            'classroom_id',
        ], $params)->execute();
    }

    public function processing()
    {
        parent::processing();
        if ($this->getImportTotalNumber() > $this->_limitUser) {
            $this->csv[] = ' , 导入用户不能超过' . $this->_limitUser . '行';
            return false;
        }
        if ($this->hasErrorCsv()) {
            return false;
        }
        $id = [];
        $users = (new User())->find()->where(['username' => $this->username])->all();
        foreach ($users as $user){
            $id[] = $user->id;
        }
        User::deleteAll(['id' => $id]);
        UserTeacher::deleteAll(['id' => $id]);
        UserTeacherClassroom::deleteAll(['user_id' => $id]);

        $this->batchInsertUser($this->user);
        $this->batchInsertUserTeacher($this->userTeacher);
        $this->batchInsertUserTeacherClassroom($this->userTeacherClassroom);
        foreach ($this->classroom as $classroom) {
            $classroom->save(false);
        }
        return true;
    }
}